﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BTKERP.Model;
using BTKERP.BLL.Inventory;
using BTKERP.MVCWeb.AppCode;
using System.Collections;

namespace BTKERP.MVCWeb.Controllers
{
    public class RequistionController : RestrictController
    {
        //
        // GET: /Requistion/
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            ViewBag.CurrentPageId = 3;
        }

        public ActionResult Index(string errorMessage = "")
        {
            ViewData["UserList"] = GetUserList(SessionEntity.Staff.UserName);
            ViewData["ErrorMessage"] = errorMessage;

            ViewData["WareHouseLisst"] = DataRefHelper.GetWareHouseList();
            return View();
        }

        [HttpPost]
        public ActionResult AddDetail(FormCollection formValue)
        {
            string fromHouesId = formValue.Get("fromHouse");
            string toHouseId = formValue.Get("toHouse");
            string requestCode = formValue.Get("reqCode");
            string requestBy = formValue.Get("UserList");
            DateTime requestDate = DateTime.ParseExact(formValue.Get("requisitionDate"), "MM/dd/yyyy", null);
            DateTime deliveryDate = DateTime.ParseExact(formValue.Get("deliveryDate"), "MM/dd/yyyy", null);

            if (fromHouesId == toHouseId)
            {
                return RedirectToAction("Index", new { errorMessage = "Same Warehouse found!" });
            }

            if (string.IsNullOrEmpty(requestCode))
            {
                return RedirectToAction("Index", new { errorMessage = "Invalid Requision Code!" });
            }

            string result = InventoryActivityMgt.AddNewRequisition(new Guid(fromHouesId), new Guid(toHouseId), requestCode, requestDate, SessionEntity.Staff.UserName,
                requestBy, SessionEntity.Staff.UserName, deliveryDate);

            if (result == "-1")
            {
                return RedirectToAction("Index", new { errorMessage = "Requision Code Already Exists!" });
            }
            else if (result == "0")
            {
                return RedirectToAction("Index", new { errorMessage = "Add requisioin fail!" });
            }

            return RedirectToAction("AddDetail", new { id = result });
        }

        [HttpGet]
        public ActionResult AddDetail(string id,string errorMessage="")
        {
            if (string.IsNullOrEmpty(id))
            {
                return RedirectToAction("Index");
            }

            ViewData["ErrorMessage"] = errorMessage;

            Guid masterId  ; 
            try
            {
                masterId = new Guid(id);
            }
            catch(Exception e)
            {
                 return RedirectToAction("Index");
            }

           RequisitionMaster master =   InventoryActivityMgt.GetRequisitionMasterById(masterId);
            if (master == null) return RedirectToAction("Index");
            List<SelectListItem> housed = DataRefHelper.GetWareHouseList();
            List<SelectListItem> house1 = (from k in housed select new SelectListItem(){Text = k.Text, Value = k.Value}).ToList();
            housed.ForEach((n)=>{
                if (n.Value == master.FromWarehouseId.ToString()) n.Selected = true; 
            });
            ViewData["fromHouse"] = housed;

            house1.ForEach((n) =>
            {
                if (n.Value == master.ToWarehouseId.ToString()) { n.Selected = true; } else { n.Selected = false; } 
            });
            ViewData["toHouse"] = house1;
            ViewData["UserList"] = GetUserList(master.RequisitionedBy);

            List<Product> productList = InventoryInfoMgt.GetProducts();
            List<RequisitionDetail> details = InventoryActivityMgt.GetRequisitionDetailByMasterId(masterId);
            if (details == null) details = new List<RequisitionDetail>();

            ArrayList array = new ArrayList();
            array.Add(master);
            array.Add(details);
            array.Add(productList);
            return View(array);
        }

        [HttpPost]
        public ActionResult Add(FormCollection formValue)
        {
            string masterId = formValue.Get("masterid");
            string actionType = formValue.Get("actionType");          
            string toHouseId = formValue.Get("toHouse");
            string requestBy = formValue.Get("UserList");
            string reqCode = formValue.Get("reqCode");
            DateTime requestDate = DateTime.ParseExact(formValue.Get("requisitionDate"), "MM/dd/yyyy", null);
            DateTime deliveryDate = DateTime.ParseExact(formValue.Get("deliveryDate"), "MM/dd/yyyy", null);

            List<Product> products = InventoryInfoMgt.GetProducts();
            int totalNumber = 0;
            foreach (Product product in products)
            {
                int quality = 0;
                string unitId;

                if (!int.TryParse(formValue.Get("number|" + product.Id.ToString()),out quality))
                {
                    return RedirectToAction("AddDetail", new {id=masterId, errroMessage="Invalid quantity for "+product.Name });
                }

                unitId = formValue.Get("unit|" + product.Id.ToString());
                totalNumber += quality;

                InventoryActivityMgt.UpdateRequisitionDetailProcess(new Guid(masterId), product.Id, new Guid(unitId), quality, SessionEntity.Staff.UserName);
            }

            InventoryActivityMgt.UpdateRequisitionMaster(new Guid(masterId), new Guid(toHouseId), reqCode, requestDate, requestBy, deliveryDate, totalNumber,actionType == "1" ? 0 : 1 , SessionEntity.Staff.UserName);

            if (actionType == "1")
            return RedirectToAction("AddDetail", new { id = masterId });

            return RedirectToAction("Management");
        }

        public ActionResult MyReq()
        {
            List<RequisitionMaster> masters = InventoryActivityMgt.GetRequisitionMasters().FindAll(n => n.Status == 0 && n.CreatedBy == SessionEntity.Staff.UserName);

            return View(masters);
        }

        [HttpPost]
        public JsonResult Void(string id )
        {
            if (InventoryActivityMgt.RejectMaster(id, SessionEntity.Staff.UserName))
            {
                return Json(new { Message = "Reject Successful!" });
            }
            else 
            {
                return Json(new { Message = "Reject Failed!" });
            }
        }


        public ActionResult Management()
        {
            ViewData["WareHouseLisst"] = DataRefHelper.GetWareHouseList(false);
            ViewData["UserList"] = GetUserList(SessionEntity.Staff.UserName);
            return View();
        }

        [HttpPost]
        public ActionResult Management(FormCollection collection)
        {
            ViewData["WareHouseLisst"] = DataRefHelper.GetWareHouseList();
            ViewData["UserList"] = GetUserList(SessionEntity.Staff.UserName);

            string houseId = collection.Get("house");
            string reqCode = collection.Get("requeCode");
            string reqDate = collection.Get("requeDate");
            string user = collection.Get("UserList");
            int status = int.Parse(collection.Get("status"));

            List<RequisitionMaster> requisitions = InventoryActivityMgt.SearchRequisitionMaster(houseId, reqCode, reqDate, user, status);

            return View(requisitions);
        }

        public ActionResult Detail(string id)
        {
            RequisitionMaster master = InventoryActivityMgt.GetRequisitionMasterById(new Guid(id));
            List<RequisitionDetail> details =    InventoryActivityMgt.GetRequisitionDetailByMasterId(new Guid(id));
            ArrayList array = new ArrayList();
            array.Add(master);
            array.Add(details);
            return View(array);
        }

        public ActionResult Approve(string id,string errorMessage="")
        {
            ViewData["masterId"] = id; 
            RequisitionMaster master = InventoryActivityMgt.GetRequisitionMasterById(new Guid(id));
            if (master.Status != 1)
                return RedirectToAction("Management");
            List<RequisitionDetail> details = InventoryActivityMgt.GetRequisitionDetailByMasterId(new Guid(id));
            ArrayList array = new ArrayList();
            array.Add(master);
            array.Add(details);
            return View(array);
        }

        [HttpPost]
        public ActionResult Approve(FormCollection formValue)
        {
            string actionType = formValue.Get("actionType");
            string masterId = formValue.Get("masterId");

            if (actionType == "2") //reject
            {
                InventoryActivityMgt.RejectMaster(masterId,SessionEntity.Staff.UserName);
                return RedirectToAction("Management");
            }
            
            List<RequisitionDetail> details = InventoryActivityMgt.GetRequisitionDetailByMasterId(new Guid(masterId));
            foreach (var detail in details)
            {
                int modifiedNumber = int.Parse(formValue.Get("number|" + detail.ProductId.ToString()));
                if (modifiedNumber == 0)
                {
                    InventoryActivityMgt.DeleteRequisitionDetail(new Guid(masterId), detail.ProductId);
                }
                else if (modifiedNumber != (int)detail.RequestedQty)
                {
                    InventoryActivityMgt.UpdateRequisitionDetailProcess(new Guid(masterId), detail.ProductId, detail.UnitId, modifiedNumber, SessionEntity.Staff.UserName);
                }
            }

            string results = InventoryActivityMgt.ApproveMaster(masterId, SessionEntity.Staff.UserName);
            if (results == "0")
            {
                return RedirectToAction("Approve", new { id = masterId, errorMessage = "Please check the quantity.It's out of order!" });
            }
            else
                return RedirectToAction("Management");

        }
    }
}
